package com.zzb.weixin.servlet;

import com.zzb.util.StringUtil;
import com.zzb.weixin.WeiXinApi;
import com.zzb.weixin.WeiXinService;
import com.zzb.weixin.WeiXinUtil;
import com.zzb.weixin.constant.WXUrlName;
import com.zzb.weixin.exception.WeiXinException;
import com.zzb.weixin.json.JsonObject;
import com.zzb.weixin.model.AccessToken;
import com.zzb.weixin.model.datacube.Merchandise;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * 处理微信服务器请求的Servlet URL地址：http://xxx/signature
 * 
 * 注意：官方文档限制使用80端口哦！
 * 
 */
public class WinXinXDServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static WeiXinUtil weiXinUtil = null;

	@Override
	public void init() throws ServletException {
		super.init();
		weiXinUtil = new WeiXinUtil();
	}

	/**
	 * 处理微信服务器验证
	 * 
	 */
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		try {

			AccessToken accessToken = WeiXinUtil.getAccessToken("wx419031819ba39107", "b30bf479a4bb85925b0feaf0f9cdd5d9");
			Merchandise merchandise = WeiXinUtil.getMerchandise(accessToken.getAccessToken(), "pzzwjt_DyK921rkIlRHHhxPX8TtA");

			JsonObject jo = new JsonObject();
			jo.put("count",merchandise.getQuantity());
			
			Writer out = response.getWriter();
			response.setContentType("text/json; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			String callback = request.getParameter("callback");
			if (!StringUtil.isEmpty(callback)) {
				out.write(callback+"("+jo.toString()+")");
			}else{
				out.write(jo.toString());
			}
			out.flush();
			out.close();
		} catch (WeiXinException e) {
			e.printStackTrace();
		}
	}
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}
}
